<?php
include 'checkLogin.php';

@$noPayOrderId = $_REQUEST['noPayOrderId'];
@$goodsId = $_REQUEST['goodsId'];
@$count = $_REQUEST['countInput'];

include 'db/li.php';

@$stock = dbSelect('select stock from goods where id=:id',array('id'=>$goodsId));
if($count + 5 > $stock['stock']){
	$mes = '库存不足';
	include 'index.php';
	die;
}

if(!empty($noPayOrderId)&&!empty($goodsId)){
	@$flog = dbInsert("insert into goods_order(goodsId,orderId,count) values(:goodsId,:orderId,:count)",
			array('goodsId'=>$goodsId,'orderId'=>$noPayOrderId,'count'=>$count));		//加商品
	if(!$flog){
		$mes = '添加失败,不能添加重复商品';
		include 'index.php';
		die;
	}
	@$goods_orders = dbSelectAll('select sellPrice,`count` from goods_order join goods on goods_order.goodsId=goods.id where goods_order.orderId=:id',
								array('id'=>$noPayOrderId));		//改总价
	$price = 0;
	foreach ($goods_orders as $goods_order){
		$price += $goods_order['sellPrice']*$goods_order['count'];
	}
	@$priceFlog = dbUpdate("update `order` set goodsPrice=:goodsPrice where id=:id",
			array('goodsPrice'=>$price,'id'=>$noPayOrderId));
	if(!$priceFlog){
		$mes = '获取价格失败';
		include 'index.php';
		die;
	}
			//减库存
	$newStock = $stock['stock'] - $count;
	@$countFlog = dbUpdate('update goods set stock=:stock where id=:id',array('stock'=>$newStock,'id'=>$goodsId));
	if(!$countFlog){
		$mes = '库存修改失败';
		include 'index.php';
		die;
	}
	@$stock = dbSelect('select stock from goods where id=:id',array('id'=>$goodsId));
	if($stock['stock'] <= 5){			//改销售状态
		$flog = dbUpdate("update goods set sellStatus='缺货' where id=:id",array('id'=>$goodsId));
		if(!$flog){
			$mes = '修改销售状态失败';
			include 'index.php';
			die;
		}
	}
}
header('Refresh:0;url=/index.php?goodsId='.$goodsId.'&&noPayOrderId='.$noPayOrderId);




